package com.ming.reggie.controller;

import com.ming.reggie.common.R;
import com.ming.reggie.entity.User;
import com.ming.reggie.service.UserService;
import com.ming.reggie.util.SMSUtils;
import com.ming.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.PipedReader;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UseController {
    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    //处理发送短信的请求
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码:"+code);
        //发哦是哪个手机验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //将验证码存入session
        //session.setAttribute(user.getPhone(),code);
        //将验证码存储到缓存中,并设置过期时间5分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        //返回数据,输出成功
        return R.success("发送验证码成功");
    }

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        //1.从map获取数据
        String phone = map.get("phone");
        String code = map.get("code");
        //2.从session获取手机号
        //String sessionCode = (String) session.getAttribute(phone);
        //从缓存中获取验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);
        //3.调用业务层进行登录,返回对象
        User loginUser = userService.login(phone, code, sessionCode);
        if(loginUser != null){
            //4.登录用户有效,写入用户的id到session
            session.setAttribute("user",loginUser.getId());
            //登录成功后,将session的验证码删除
            //session.removeAttribute(phone);
            //将缓存中的验证码删除
            redisTemplate.delete(phone);
            //返回成功数据
            return R.success(loginUser);
        }
        return R.error("登录失败");
    }

}
